package com.qindian.coupontest;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qindian.GoodsAdapter;
import com.qindian.model.GoodsModel;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Author: Li
 * Date: 2018/4/28 0028
 * Description:
 */

public class GoodFragment extends BaseFragment implements OnRefreshLoadmoreListener {
    private static final String KEY = "Ypj7fmVAEwyHRcIH6BoBVg3xbGidvnzk";
    private static final String AGENT_ID = "9240";
    private static final String MOBILE = "18852996181";
    private Context mContext;
    private GoodsAdapter mGoodsAdapter;
    private int mPage = 1;
    private boolean mIsRefresh = true;
    private int mGap;
    private String mPlatform;
    private String mType;
    private RecyclerView mRecyclerGoods;
    private SmartRefreshLayout mLayoutRefresh;
    private boolean mIsFirst=true;
    public static GoodFragment newInstance(String platform,String type) {

        Bundle bundle = new Bundle();
        bundle.putString("platform",platform);
        bundle.putString("type",type);
        GoodFragment fragment = new GoodFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext=context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_goods,container,false);
        mPlatform=getArguments().getString("platform");
        mType=getArguments().getString("type");
        mRecyclerGoods = view.findViewById(R.id.recycler_goods);
        mLayoutRefresh = view.findViewById(R.id.layout_refresh);
        mGap = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5f, getResources().getDisplayMetrics());

        mGoodsAdapter = new GoodsAdapter(R.layout.item_goods_coupon,mType);
        mRecyclerGoods.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerGoods.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(0, mGap, 0, mGap);
            }
        });
        mGoodsAdapter.bindToRecyclerView(mRecyclerGoods);
        mGoodsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsModel.DataBean.ListBean bean = mGoodsAdapter.getData().get(position);
                exchangeCoupon(mType, bean.getId(), MOBILE);
            }
        });
        mLayoutRefresh.setOnRefreshLoadmoreListener(this);
        if (mType.equals("tb")) {
            getGoodsList(1);
        }
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser&&getArguments() != null) {
            if (mIsFirst && !TextUtils.isEmpty(mType) &&mType.equals("jd")) {
                mIsFirst=false;
                getGoodsList(1);
            }
        }
    }

    /**
     * 获取优惠商品列表
     *
     * @param page 页码
     */
    private void getGoodsList(int page) {
        if (mGoodsAdapter.getData().size() == 0) {
            showLoadingDialog();
        }
        Map<String, Object> map = new HashMap<>();
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        String prefix = "agent_id=" + AGENT_ID + "&page=" + page;
        String token = MD5Util.getMD5(prefix + time + KEY);
        map.put("agent_id", AGENT_ID);
        map.put("time", time);
        map.put("token", token);
        map.put("page", page);
        RetrofitHelper.createService().getGoodsList(mPlatform, map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GoodsModel>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }
                    @Override
                    public void onNext(GoodsModel goodsModel) {
                        dismissLoadingDialog();
                        if (mIsRefresh) {
                            mPage = 1;
                            mGoodsAdapter.setNewData(goodsModel.getData().getList());
                            if (goodsModel.getData().getTotal()
                                    > mGoodsAdapter.getData().size()) {
                                mLayoutRefresh.setLoadmoreFinished(false);
                            } else {
                                mLayoutRefresh.setLoadmoreFinished(true);
                            }
                        } else {
                            mGoodsAdapter.addData(goodsModel.getData().getList());
                            if (goodsModel.getData().getTotal()
                                    > mGoodsAdapter.getData().size()) {
                                mPage++;
                                mLayoutRefresh.setLoadmoreFinished(false);
                            } else {
                                mLayoutRefresh.setLoadmoreFinished(true);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        stopRefreshLoad();
                        showToast("网络连接错误");
                    }

                    @Override
                    public void onComplete() {
                        stopRefreshLoad();
                    }
                });
    }

    /**
     * 兑换优惠券
     * @param type  兑换渠道 jd/tb
     * @param gid   商品id
     * @param mobile    兑换手机号
     */
    private void exchangeCoupon(String type, String gid, String mobile) {
        showLoadingDialog("正在兑换...");
        String time = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("gid", gid);
        map.put("mobile", mobile);
        map.put("agent_id", AGENT_ID);
        map.put("time", time);

        String prefix = "agent_id=" + AGENT_ID + "&gid=" + gid + "&mobile=" + mobile + "&type=" + type;
        String token = MD5Util.getMD5(prefix + time + KEY);
        map.put("token", token);


        Log.e("tag", "exchangeCoupon: "+type+"|"+gid+"|"+mobile+"|"+AGENT_ID+"|"+time+"|"+token+"|"+
        prefix+time+KEY);
//        RetrofitHelper.createService().exchangeCoupon(map)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<ExchangeModel>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(ExchangeModel exchangeModel) {
//                        if (exchangeModel.getCode().equals("000000")) {
//
//                        }else {
//                            showToast(exchangeModel.getMsg());
//
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        showToast(e.toString());
//                        dismissLoadingDialog();
//                    }
//
//                    @Override
//                    public void onComplete() {
//                        dismissLoadingDialog();
//                    }
//                });

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mIsRefresh = false;
        getGoodsList(mPage + 1);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mIsRefresh = true;
        getGoodsList(1);
    }

    private void stopRefreshLoad() {
        mLayoutRefresh.finishRefresh();
        mLayoutRefresh.finishLoadmore();
    }
}
